package com.liuyi.security;

import com.fmy.mcsecurity.login.service.McUserDetails;
import com.liuyi.tools.kits.RequestKit;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Mr.fmy
 * @version 1.0.0
 * @ClassName SecurityKit
 * @Description TODO Security工具集
 * @createTime 2020/5/6 16:12
 */
public class SecurityKit {

    public static String getToken() {
        return RequestKit.getRequest().getHeader(SecurityAbstractConfig.TOKEN_KEY).replace(SecurityAbstractConfig.TOKEN_BEARER_KEY, "");
    }

    /**
     * 获取 Authentication
     *
     * @return {@linkplain Authentication}
     */
    public static Authentication getAuthentication() {
        SecurityContext context = SecurityContextHolder.getContext();
        if (context != null) {
            return context.getAuthentication();
        }
        return null;
    }


    /**
     * 获取 当前用户认证信息
     *
     * @param c   认证信息类Class
     * @param <T> 认证信息类
     * @return <T>
     */
    @SuppressWarnings("unchecked")
    public static <T> T getDetail(Class<T> c) {
        Authentication a = getAuthentication();
        if (a != null) {
            if (c.isInstance(a.getPrincipal())) {
                return (T) a.getPrincipal();
            }
        }
        return null;
    }

    /**
     * 获取当前登录人id
     */
    public static String getUserId() {
        Authentication a = getAuthentication();
        if (a != null) {
            if (a.getPrincipal() instanceof McUserDetails) {
                return ((McUserDetails) a.getPrincipal()).userId();
            }
        }
        return null;
    }

    /**
     * 获取权限code集合
     */
    public static List<String> getAuthorities() {
        Authentication a = getAuthentication();
        List<String> authorities = new ArrayList<>();
        if (a != null) {
            a.getAuthorities().forEach(item -> {
                authorities.add(item.getAuthority());
            });
        }
        return authorities;
    }
}
